﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Web.Mvc;
using Cost.Models;
using Cost.Services;
using NBlock.Core;
using NBlock.MVCExtensions;
using Cost.Services.Services;

namespace Cost.Controllers
{
    public class StorageController : Controller
    {
        #region 构造函数
        private readonly ICostRepository<Storage> storageRepository;
        private readonly MaterialService materialService;
        private readonly StorageService storageService;

        public StorageController(ICostRepository<Storage> storageRepository,
            StorageService storageService,
            MaterialService materialService)
        {
            this.storageRepository = storageRepository;
            this.materialService = materialService;
            this.storageService = storageService;
        }
        #endregion

        public ActionResult Index(string type)
        {
            ViewBag.Title = type == "RawMaterial" ? "原材料库存" : "半成品库存";
            ViewBag.Type = type;
            return View();
        }

        [HttpPost]
        public JsonResult List(string type, nbPageInfo pager, nbSearchCondition where)
        {
            Expression<Func<Storage, bool>> filter = null;
            if (type == "RawMaterial")
                filter = filter.And(m => m.NeedProcess == false);
            else
                filter = filter.And(m => m.NeedProcess == true);

            var pagedata = storageRepository.GetPageable(pager, filter, where);

            var list = new List<Storage>(pagedata.Page.Count());
            foreach (var data in pagedata.Page)
            {
                data.CurrentPrice = materialService.GetMaterialPrice(data.MaterialId, data.NeedProcess);
                list.Add(data);
            }
            return Json(pager.ToGridData(list, pagedata.Total));
        }

        #region 盘点

        public ActionResult Inventory()
        {
            return View();
        }

        [HttpPost]
        public JsonResult InventoryList(nbPageInfo pager, nbSearchCondition where)
        {
            var pageData = storageRepository.GetPageable(pager, where);
            var data = pager.ToGridData(pageData);
            return Json(data);
        }

        public ActionResult InventoryEdit(string Id)
        {
            var data = storageRepository.Find(Id) ?? new Storage();
            return View(data);
        }

        [HttpPost]
        public JsonResult InventorySave(string Id)
        {
            var data = storageRepository.Find(Id) ?? new Storage();
            TryUpdateModel(data);
            storageRepository.Save(data);
            storageService.StorageIn(data.MaterialId, data.ActualStorage.Value, "盘点库存");

            return Json(nbAjaxMessage.Successful);
        }
        #endregion
    }
}
